<template>
	<view class="wrap">
		<view class="search-section">
			<view class="search">
				<u-search v-model="queryChannelForm.customerName" placeholder="请输入客户名称" :show-action="true"
					@custom="querySearch" @search="querySearch">
				</u-search>
				<view class="filter-btn" @click="showFilterPopup">
					<view class="filter-icon">
						<image src="/static/icon_filter.svg" style="width: 25px;height: 25px;"></image>
					</view>
					<!-- <view class="filter-text">筛选</view> -->
				</view>
			</view>
			<scroll-view scroll-x class="filter-tags" show-scrollbar="false">
				<view class="tag-list">
					<u-button shape="circle" v-for="(tag, index) in filterTags" :key="index" :text="tag.text"
						:type="tag.active ? 'error' : 'default'" @click="toggleFilter(index)" size="small" />
				</view>
			</scroll-view>
		</view>

		<scroll-view style="width: 100vw;height: 80vh;" scroll-y enable-back-to-top="true" class="order-scroll"
			:refresher-enabled="true" :refresher-triggered="refresherTriggered" @refresherrefresh="refresherrefresh"
			@scrolltolower="reachBottom">
			<template v-if="loading">
				<view class="skeleton-loading" v-for="i in 3" :key="i">
					<view class="skeleton-card">
						<view class="skeleton-header"></view>
						<view class="skeleton-content">
							<view class="skeleton-image"></view>
							<view class="skeleton-info">
								<view class="skeleton-line"></view>
								<view class="skeleton-line"></view>
							</view>
						</view>
					</view>
				</view>
			</template>

			<view v-else-if="listChannel.length === 0" class="empty-state">
				<uni-icons type="info" size="64" color="#999"></uni-icons>
				<text>暂无订单信息</text>
			</view>

			<view v-else class="order-list">
				<view class="order-item" v-for="(item, index) in listChannel" :key="index">
					<view class="order-card">
						<!-- 订单头部 -->
						<view class="order-header">
							<view class="order-number">
								<text class="label">单据编号</text>
								<uni-tag custom-style="font-weight: bold;" :inverted="true" type="warning"
									:text="`${item.billNumber}`"></uni-tag>
							</view>
							<!-- <view style="width: fit-content;">
								<u-button @click="searchProcess(item.billNumber)" type="error" size="mini"
									shape="circle">流程</u-button>
							</view> -->
							<image :src="getBillStatusText(item.billStatus,item.completionStatus)"
								style="width: 80px;height: 40px;" mode="widthFix">
							</image>
						</view>

						<!-- 订单内容 -->
						<view class="order-content" @click="redirectChanneInfo(item)">
							<image class="goods-image" :src="item.goodsImg" mode="aspectFill"
								@error="handleImageError" />
							<view class="order-details">
								<view class="customer-info">
									<text class="name">{{ item.customerName }}</text>
									<text class="time">{{ formatDate(item.createTime) }}</text>
								</view>
								<view class="account-info" v-if="item.cancelMsg">
									<text class="bank" style="color: #ff0000;">驳回原因:{{ item.cancelMsg }}</text>
								</view>
								<view class="account-info">
									<text class="bank">{{ item.bankAccount }}</text>
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>

			<uni-load-more :status="loadStatus" :content-text="loadMoreText"></uni-load-more>
		</scroll-view>
		<!-- 筛选弹出框 -->
		<uni-popup ref="filterPopup" type="top">
			<view class="filter-popup">
				<view class="filter-header">
					<text>订单筛选</text>
					<text class="close-icon" @click="closeFilterPopup">✕</text>
				</view>

				<view class="filter-content">
					<text class="section-title">创建时间</text>
					<view class="time-options">
						<view v-for="(item, index) in timeOptions" :key="index"
							:class="['time-option', selectedTime === item.value ? 'active' : '']"
							@click="selectTimeOption(item.value)">
							{{ item.label }}
						</view>
					</view>
					<view class="date-range">
						<uni-datetime-picker start-placeholder="起始时间" end-placeholder="终止时间" v-model="rangeDate"
							type="daterange" @change="handleDateChange" />
					</view>

					<view class="filter-footer">
						<button class="reset-btn" @click="resetFilter">重置</button>
						<button class="confirm-btn" @click="confirmFilter">确认</button>
					</view>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import {
		selectGoodsInfo,
		goodInfoDetail,
		getMindMap
	} from '@/api/goods/goods.js';
	export default {
		onLoad: function(swiperCurrent) {
			this.querySearch();
			// 监听刷新事件
			uni.$on('refreshPage', () => {
				// 在这里执行刷新操作，例如重新获取数据
				this.querySearch();
			});
		},
		data() {
			return {

				viewMode: 'list',
				currentTab: 0,
				swiperCurrent: 0,
				listChannel: [],
				goodInfoDetail: [],
				loadStatus: 'noMore',
				loadChannelList: false,
				loadTerminalList: false,
				emptyTips: {
					type: String,
					default: ''
				},
				queryChannelForm: {
					customerName: '',
					bullStatus: '',
					pageNum: 1,
					pageSize: 10,
					startDate: '',
					endDate: '',
					selectedTime: '',
				},
				queryGoodsInfo: {
					billNumber: ''
				},
				refresherTriggered: false,
				_refresherTriggered: false,
				loading: true,
				showAnimation: false,
				filterTags: [{
						text: '全部',
						active: true
					},
					{
						text: '未提报',
						active: false
					},
					{
						text: '已提报',
						active: false
					},
					{
						text: '被驳回',
						active: false
					},
					{
						text: '已审核',
						active: false
					},
				],
				loadMoreText: {
					contentdown: '上拉显示更多',
					contentrefresh: '加载中...',
					contentnomore: '没有更多数据了'
				},
				selectedTime: '',
				timeOptions: [{
						label: '近一周',
						value: '7/30'
					},
					{
						label: '近1个月',
						value: '1'
					},
					{
						label: '近3个月',
						value: '3'
					}
				],
				rangeDate: [],
			}
		},
		onShow() {
			this.getSelectGoodsInfo()
		},
		methods: {
			handleDateChange(e) {
				this.rangeDate = e
				this.selectedTime = ''
			},
			// 筛选弹出框
			showFilterPopup() {
				this.$refs.filterPopup.open();
			},
			// 关闭筛选弹出框
			closeFilterPopup() {
				this.$refs.filterPopup.close();
			},
			// 选择时间
			selectTimeOption(value) {
				this.selectedTime = value;
				this.rangeDate = []; // 清空日期范围
			},
			// 重置筛选
			resetFilter() {
				this.selectedTime = '';
				this.rangeDate = [];
			},
			confirmFilter() {
				if (this.selectedTime) {
					let [startDate, endDate] = getRecentRange(this.selectedTime)
					this.queryChannelForm.startDate = endDate
					this.queryChannelForm.endDate = startDate
				} else {
					let [startDate, endDate] = this.rangeDate
					this.queryChannelForm.startDate = startDate
					this.queryChannelForm.endDate = endDate
				}
				this.closeFilterPopup();
				this.querySearch()

				function getRecentRange(value) {
					const endDate = new Date();
					const startDate = new Date(endDate);
					if (value === '7/30') {
						// 近一周
						startDate.setDate(endDate.getDate() - 7);
					} else {
						// 按月份计算
						startDate.setMonth(endDate.getMonth() - parseInt(value));
					}
					return [formatDate(endDate), formatDate(startDate)];
				}

				// 格式化日期为 'YYYY-MM-DD' 格式
				function formatDate(date) {
					const year = date.getFullYear();
					const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，所以+1
					const day = String(date.getDate()).padStart(2, '0');
					return `${year}-${month}-${day}`;
				}
			},
			searchProcess(billStatus) {
				uni.navigateTo({
					url: `/pages/mindmap/trackInfo?billStatus=${billStatus}`
				});
			},
			querySearch() {
				this.loading = true;
				this.listChannel = [];
				this.getSelectGoodsInfo().then(() => {
					this.loading = false;
					this.showAnimation = true;
				}).catch(err => {
					console.error('加载数据失败:', err);
					this.loading = false;
				});
			},
			getSelectGoodsInfo() {
				this.loadStatus = "loading";
				if (!this.loadChannelList) {
					this.loadChannelList = true;
				}
				this.listChannel = [];
				return new Promise((resolve, reject) => {
					selectGoodsInfo(this.queryChannelForm).then(res => {
						try {
							for (let i = 0; i < res.rows.length; i++) {
								this.listChannel.push(res.rows[i]);
							}

							if ((this.queryChannelForm.pageNum * this.queryChannelForm.pageSize) < res
								.total) {
								this.loadChannelList = false;
								this.loadStatus = "loadmore";
							} else {
								this.loadChannelList = true;
								this.loadStatus = "nomore";
							}
							resolve(res);
						} catch (err) {
							reject(err);
						}
					}).catch(err => {
						this.loadStatus = "nomore";
						reject(err);
					});
				});
			},
			onPullDownRefresh() {
				setTimeout(function() {
					uni.stopPullDownRefresh();
				}, 1000);
			},
			redirectChanneInfo(item) {
				//goodInfoDetail goodsImg
				// console.log(item)
				this.queryGoodsInfo.billNumber = item.billNumber
				goodInfoDetail(this.queryGoodsInfo).then(res => {
					this.goodInfoDetail = res
					// console.log(this.goodInfoDetail)
					// 跳转到 /pages/goods/dispatch 页面并传递数据
					uni.navigateTo({
						url: `/pages/goods/dispatch?goodInfoDetail=${JSON.stringify(this.goodInfoDetail)}&needDataFeedback=true&billNumber=${item.billNumber}&pictureUrl=${item.goodsImg}`
					});
				})
			},
			getBillStatusText(status, completionStatus) {
				if (completionStatus == '1') {
					return 'https://henanhanyong1995.oss-cn-hangzhou.aliyuncs.com/WeChatUploadImg/已完成.png';
				}
				switch (status) {
					case '0':
						return 'https://henanhanyong1995.oss-cn-hangzhou.aliyuncs.com/WeChatUploadImg/未提报.png';
					case '1':
						return 'https://henanhanyong1995.oss-cn-hangzhou.aliyuncs.com/WeChatUploadImg/已提报.png';
					case '2':
						return 'https://henanhanyong1995.oss-cn-hangzhou.aliyuncs.com/WeChatUploadImg/驳回.png';
					case '3':
						return 'https://henanhanyong1995.oss-cn-hangzhou.aliyuncs.com/WeChatUploadImg/审核通过.png';
					default:
						return '未知状态';
				}
			},
			getBillStatusType(status) {
				const typeMap = {
					'0': 'warning',
					'1': 'primary',
					'2': 'error',
					'3': 'success'
				};
				return typeMap[status] || 'default';
			},
			toggleFilter(index) {
				this.filterTags.forEach((tag, i) => {
					tag.active = i === index;
				});
				if (index == '0') {
					this.queryChannelForm.billStatus = null;
				} else {
					this.queryChannelForm.billStatus = index - 1;
				}
				this.querySearch();
			},
			reachBottom() {
				if (!this.listChannel) {
					this.queryChannelForm.pageNum += 1;
					this.querySearch();
				} else {
					this.loadStatus = "nomore"
				}
			},
			refresherrefresh() {
				if (this._refresherTriggered) return; // 防止多次触发
				this._refresherTriggered = true;

				// 重置数据
				this.refresherTriggered = true;
				this.queryChannelForm.pageNum = 1; // 重置页码
				this.listChannel = []; // 清空数据

				this.querySearch(); // 重新加载数据

				// 结束下拉刷新动画
				setTimeout(() => {
					this.refresherTriggered = false;
					this._refresherTriggered = false;
				}, 800); // 动画时间
			},
			handleImageError(e) {
				console.error('图片加载失败', e);
			},
			formatDate(dateString) {
				const date = new Date(dateString);
				return `${date.getMonth() + 1}/${date.getDate()} ${date.getHours()}:${date.getMinutes()}`;
			},
		},
		onUnload() {
			const pageFlag = wx.getStorageSync('pageFlag');
			const pageLength = getCurrentPages();
			if (pageLength.length > 2 && pageFlag) {
				wx.removeStorageSync('pageFlag')
				uni.navigateBack()
			}
		},
	}
</script>

<style lang="scss" scoped>
	.wrap {
		display: absolute;
		flex-direction: column;
		/* height: calc(100vh - var(--window-top)); */
		width: 100%;
		background-color: #f5f5f5;

		.search-section {
			background: #fff;
			padding: 10px;
			position: sticky;
			top: 0px;
			z-index: 100;

			.search {
				display: flex;
				justify-content: space-between;
				align-items: center;

				.filter-btn {
					display: flex;
					flex-direction: column;
					justify-content: space-between;
					align-items: center;
					padding: 5px 5px 0;

					.account-text {
						font-size: 14px;
						font-weight: 500;
						color: #333;
					}
				}

			}

			.filter-tags {
				margin-top: 10px;
				white-space: nowrap;
				height: 30px;
				line-height: 30px;

				.tag-list {
					display: inline-flex;
					gap: 8px;
					padding: 0 10px;
				}
			}
		}

		.order-scroll {
			flex: 1;
		}

		.order-item {
			opacity: 1;
			transform: none;
			animation: none;
		}

		.empty-state {
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			padding: 40px;
			color: #999;

			text {
				margin-top: 10px;
			}
		}

		.skeleton-loading {
			padding: 10px;

			.skeleton-card {
				background: #fff;
				border-radius: 8px;
				padding: 15px;
				margin-bottom: 10px;

				.skeleton-header {
					height: 20px;
					background: #f0f0f0;
					margin-bottom: 15px;
					border-radius: 4px;
					animation: shimmer 1s infinite linear;
				}

				.skeleton-content {
					display: flex;
					gap: 15px;

					.skeleton-image {
						width: 120px;
						height: 120px;
						background: #f0f0f0;
						border-radius: 8px;
						animation: shimmer 1s infinite linear;
					}

					.skeleton-info {
						flex: 1;

						.skeleton-line {
							height: 16px;
							background: #f0f0f0;
							margin-bottom: 10px;
							border-radius: 4px;
							animation: shimmer 1s infinite linear;

							&:last-child {
								width: 60%;
							}
						}
					}
				}
			}
		}
	}

	.order-list {
		padding: 10px;
	}

	.order-item {
		margin-bottom: 10px;
	}

	.order-card {
		background: #fff;
		border-radius: 8px;
		overflow: hidden;
		box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);

		.order-header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 12px;
			border-bottom: 1px solid #f5f5f5;

			.order-number {
				display: flex;
				align-items: center;
				gap: 8px;

				.label {
					color: #999;
					font-size: 13px;
					font-weight: 800;
				}

				.number {
					color: #333;
					font-size: 13px;
					font-weight: 500;
				}
			}

			.process-btn {
				width: 10px !important;
			}
		}

		.order-content {
			padding: 12px;
			display: flex;
			gap: 12px;

			.goods-image {
				width: 80px;
				height: 80px;
				border-radius: 4px;
				background: #f5f5f5;
				flex-shrink: 0;
			}

			.order-details {
				flex: 1;
				display: flex;
				flex-direction: column;
				justify-content: space-between;

				.customer-info {
					display: flex;
					justify-content: space-between;
					align-items: flex-start;

					.name {
						font-size: 15px;
						font-weight: 500;
						color: #333;
					}

					.time {
						font-size: 12px;
						color: #999;
					}
				}

				.account-info {
					margin-top: 8px;

					.bank {
						font-size: 13px;
						color: #666;
					}
				}
			}
		}

		&:active {
			background: #f9f9f9;
		}
	}

	@keyframes shimmer {
		0% {
			background-position: -200% 0;
		}

		100% {
			background-position: 200% 0;
		}
	}

	.filter-popup {
		background: #fff;
		height: calc(90vh);
		// min-height: 1000rpx;
		display: flex;
		flex-direction: column;
		position: relative;
		padding-bottom: 100rpx;

		.filter-header {
			padding: 30rpx;
			text-align: center;
			position: relative;
			border-bottom: 1rpx solid #eee;

			text {
				font-size: 32rpx;
				color: #333;
			}

			.close-icon {
				position: absolute;
				right: 30rpx;
				top: 50%;
				transform: translateY(-50%);
				font-size: 32rpx;
				color: #999;
			}
		}

		.filter-content {
			flex: 1;
			padding: 30rpx;

			.section-title {
				display: block;
				font-size: 28rpx;
				color: #333;
				margin-bottom: 30rpx;
			}

			.time-options {
				display: flex;
				gap: 20rpx;
				margin-bottom: 30rpx;

				.time-option {
					flex: 1;
					height: 70rpx;
					line-height: 70rpx;
					text-align: center;
					background: #f8f8f8;
					border-radius: 4rpx;
					font-size: 28rpx;
					color: #333;

					&.active {
						background: #fff;
						color: #ff6b35;
						border: 2rpx solid #ff6b35;
					}
				}
			}

			.date-range {
				margin-top: 20rpx;
			}
		}

		.filter-footer {
			position: absolute;
			bottom: 0;
			left: 0;
			right: 0;
			display: flex;
			align-items: center;
			height: 100rpx;
			padding: 30rpx;

			button {
				flex: 1;
				border: none;
				font-size: 32rpx;
				color: #fff;

				&.reset-btn {
					background: #ffc300;
					border-top-right-radius: 0;
					border-bottom-right-radius: 0;
				}

				&.confirm-btn {
					background: #ff6b35;
					border-top-left-radius: 0;
					border-bottom-left-radius: 0;
				}
			}
		}
	}
</style>